<template>
  <div class="product-detail">
    <!-- 面包屑导航 -->
    <div class="breadcrumb">
      <div class="container">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item v-if="product?.category">
            {{ product.category.name }}
          </el-breadcrumb-item>
          <el-breadcrumb-item>{{ product?.name }}</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </div>

    <!-- 商品详情主体 -->
    <div class="container" v-loading="loading">
      <div class="product-main" v-if="product">
        <!-- 左侧：商品图片 -->
        <div class="product-images">
          <div class="main-image">
            <img
              :src="currentImage"
              :alt="product.name"
              @error="handleImageError"
            />
          </div>
          <div class="thumbnail-list" v-if="product.images && product.images.length > 1">
            <div
              v-for="(image, index) in product.images"
              :key="index"
              class="thumbnail-item"
              :class="{ active: currentImage === image }"
              @click="currentImage = image"
            >
              <img :src="image" :alt="`${product.name} ${index + 1}`" />
            </div>
          </div>
        </div>

        <!-- 右侧：商品信息 -->
        <div class="product-info">
          <h1 class="product-title">{{ product.name }}</h1>
          <p class="product-subtitle" v-if="product.subtitle">{{ product.subtitle }}</p>

          <!-- 价格信息 -->
          <div class="price-section">
            <div class="current-price">¥{{ product.price }}</div>
            <div class="original-price" v-if="product.marketPrice && product.marketPrice > product.price">
              ¥{{ product.marketPrice }}
            </div>
          </div>

          <!-- 商品标签 -->
          <div class="product-tags" v-if="hasProductTags">
            <span v-if="product.isNew" class="tag new">新品</span>
            <span v-if="product.isHot" class="tag hot">热销</span>
            <span v-if="product.isRecommend" class="tag recommend">推荐</span>
          </div>

          <!-- 商品规格选择 -->
          <div class="product-specs" v-if="product.skus && product.skus.length > 0">
            <h3>选择规格</h3>
            <div class="spec-options">
              <div
                v-for="sku in product.skus"
                :key="sku.id"
                class="spec-option"
                :class="{ active: selectedSku?.id === sku.id, disabled: sku.stockQuantity === 0 }"
                @click="selectSku(sku)"
              >
                <span>{{ formatSpecifications(sku.specifications) }}</span>
                <span class="spec-price">¥{{ sku.price }}</span>
              </div>
            </div>
          </div>

          <!-- 数量选择 -->
          <div class="quantity-section">
            <label>数量：</label>
            <el-input-number
              v-model="quantity"
              :min="1"
              :max="maxQuantity"
              size="large"
            />
            <span class="stock-info">库存：{{ currentStock }}{{ product.unit || '件' }}</span>
          </div>

          <!-- 操作按钮 -->
          <div class="action-buttons">
            <el-button
              type="primary"
              size="large"
              :disabled="currentStock === 0"
              @click="addToCart"
            >
              <el-icon><ShoppingCart /></el-icon>
              {{ currentStock === 0 ? '暂时缺货' : (isInCart ? `购物车中已有 ${cartQuantity} 件` : '加入购物车') }}
            </el-button>
            <el-button
              type="danger"
              size="large"
              :disabled="currentStock === 0"
              @click="buyNow"
            >
              立即购买
            </el-button>
          </div>

          <!-- 商品服务信息 -->
          <div class="service-info">
            <div class="service-item" v-if="product.serviceInfo">
              <el-icon><Van /></el-icon>
              <span>{{ product.serviceInfo }}</span>
            </div>
            <div class="service-item" v-if="product.shippingInfo">
              <el-icon><Van /></el-icon>
              <span>{{ product.shippingInfo }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 商品详情描述 -->
      <div class="product-description" v-if="product">
        <div class="description-header">
          <h2>商品详情</h2>
          <div class="header-divider"></div>
        </div>
        <div class="description-content">
          <div v-if="product.description" class="description-text">
            <p v-for="(paragraph, index) in product.description.split('\n')" :key="index" class="description-paragraph">
              {{ paragraph }}
            </p>
          </div>
          <div v-else class="no-description">
            <div class="no-description-icon"></div>
            <h3>暂无详细描述</h3>
            <p>商家还未添加详细的商品描述信息</p>
          </div>

          <!-- 商品亮点 -->
          <div class="product-highlights" v-if="product.keywords">
            <h3>商品亮点</h3>
            <div class="highlights-grid">
              <div
                v-for="keyword in product.keywords.split(',')"
                :key="keyword"
                class="highlight-item"
              >
                <div class="highlight-icon"></div>
                <span>{{ keyword.trim() }}</span>
              </div>
            </div>
          </div>

          <!-- 购买保障 -->
          <div class="purchase-guarantee">
            <h3>购买保障</h3>
            <div class="guarantee-grid">
              <div class="guarantee-item">
                <div class="guarantee-icon"></div>
                <div class="guarantee-text">
                  <h4>正品保证</h4>
                  <p>100%正品，假一赔十</p>
                </div>
              </div>
              <div class="guarantee-item">
                <div class="guarantee-icon"></div>
                <div class="guarantee-text">
                  <h4>快速配送</h4>
                  <p>全国包邮，48小时发货</p>
                </div>
              </div>
              <div class="guarantee-item">
                <div class="guarantee-icon"></div>
                <div class="guarantee-text">
                  <h4>售后无忧</h4>
                  <p>7天无理由退换货</p>
                </div>
              </div>
              <div class="guarantee-item">
                <div class="guarantee-icon"></div>
                <div class="guarantee-text">
                  <h4>支付安全</h4>
                  <p>多种支付方式，安全可靠</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 商品不存在的提示 -->
    <div class="not-found" v-if="!loading && !product">
      <el-empty description="商品不存在或已下架">
        <el-button type="primary" @click="$router.push('/')">返回首页</el-button>
      </el-empty>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ShoppingCart, Van } from '@element-plus/icons-vue'
import { productApi } from '@/api/product'
import type { Product } from '@/api/product'
import { useCartStore } from '@/stores/cart'
import { useOrderStore } from '@/stores/order'
import type { OrderInfo } from '@/stores/order'

const route = useRoute()
const router = useRouter()
const cartStore = useCartStore()
const orderStore = useOrderStore()

// 响应式数据
const loading = ref(false)
const product = ref<Product | null>(null)
const currentImage = ref('')
const selectedSku = ref<any>(null)
const quantity = ref(1)

// 计算属性
const hasProductTags = computed(() => {
  return product.value && (
    product.value.isNew ||
    product.value.isHot ||
    product.value.isRecommend ||
    product.value.keywords
  )
})

const currentStock = computed(() => {
  if (selectedSku.value) {
    return selectedSku.value.stockQuantity
  }
  return product.value?.stockQuantity || 0
})

const maxQuantity = computed(() => {
  return Math.min(currentStock.value, 99)
})

const isInCart = computed(() => {
  return product.value ? cartStore.isInCart(product.value.id) : false
})

const cartQuantity = computed(() => {
  return product.value ? cartStore.getItemQuantity(product.value.id) : 0
})

// 方法
const fetchProductDetail = async (id: string) => {
  try {
    loading.value = true
    const response = await productApi.getProductById(Number(id))

    if (response.code === 200 && response.data) {
      product.value = response.data
      // 设置默认图片
      if (product.value.images && product.value.images.length > 0) {
        currentImage.value = product.value.images[0]
      } else if (product.value.mainImage) {
        currentImage.value = product.value.mainImage
      }

      // 设置默认SKU
      if (product.value.skus && product.value.skus.length > 0) {
        selectedSku.value = product.value.skus[0]
      }
    } else {
      product.value = null
      ElMessage.error('商品不存在或已下架')
    }
  } catch (error) {
    console.error('获取商品详情失败:', error)
    product.value = null
    ElMessage.error('获取商品详情失败')
  } finally {
    loading.value = false
  }
}

const selectSku = (sku: any) => {
  if (sku.stockQuantity > 0) {
    selectedSku.value = sku
    quantity.value = 1 // 重置数量
  }
}

const formatSpecifications = (specs: any) => {
  if (!specs || typeof specs !== 'object') return ''
  return Object.entries(specs).map(([key, value]) => `${key}: ${value}`).join(', ')
}

const handleImageError = (event: Event) => {
  const target = event.target as HTMLImageElement
  target.src = '/placeholder.svg'
}

const addToCart = async () => {
  if (currentStock.value === 0) {
    ElMessage.warning('商品暂时缺货')
    return
  }

  if (!product.value) {
    ElMessage.error('商品信息不完整')
    return
  }

  try {
    await cartStore.addToCart(product.value, quantity.value)
  } catch (error) {
    console.error('加入购物车失败:', error)
  }
}

const buyNow = () => {
  if (currentStock.value === 0) {
    ElMessage.warning('商品暂时缺货')
    return
  }

  if (!product.value) {
    ElMessage.error('商品信息不完整')
    return
  }

  // 检查用户是否登录
  const token = localStorage.getItem('token')
  if (!token) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  // 构建订单信息
  const orderInfo: OrderInfo = {
    items: [{
      productId: product.value.id,
      skuId: selectedSku.value?.id,
      productName: product.value.name,
      productImage: product.value.mainImage || product.value.image,
      skuSpecifications: selectedSku.value?.specifications,
      price: selectedSku.value?.price || product.value.price,
      quantity: quantity.value,
      totalAmount: (selectedSku.value?.price || product.value.price) * quantity.value
    }],
    consigneeName: '',
    consigneePhone: '',
    consigneeAddress: '',
    shippingFee: 0,
    pointsAmount: 0,
    buyerMessage: '',
    totalAmount: (selectedSku.value?.price || product.value.price) * quantity.value,
    goodsAmount: (selectedSku.value?.price || product.value.price) * quantity.value
  }

  // 保存订单信息到store
  orderStore.setOrderInfo(orderInfo)

  // 跳转到订单确认页面
  router.push('/order/confirm')
}

// 监听路由变化
watch(() => route.params.id, (newId) => {
  if (newId) {
    fetchProductDetail(newId as string)
  }
}, { immediate: true })

// 生命周期
onMounted(async () => {
  // 初始化购物车
  await cartStore.initCart()

  const productId = route.params.id as string
  if (productId) {
    fetchProductDetail(productId)
  }
})
</script>

<style scoped>
.product-detail {
  min-height: 100vh;
  background: #f5f5f5;
}

.breadcrumb {
  background: white;
  padding: 15px 0;
  border-bottom: 1px solid #e0e0e0;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.product-main {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 40px;
  background: white;
  padding: 30px;
  margin: 20px 0;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 商品图片区域 */
.product-images {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.main-image {
  width: 100%;
  aspect-ratio: 1;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  overflow: hidden;
}

.main-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.thumbnail-list {
  display: flex;
  gap: 10px;
  overflow-x: auto;
}

.thumbnail-item {
  flex-shrink: 0;
  width: 80px;
  height: 80px;
  border: 2px solid transparent;
  border-radius: 6px;
  overflow: hidden;
  cursor: pointer;
  transition: border-color 0.3s;
}

.thumbnail-item.active {
  border-color: #ff6700;
}

.thumbnail-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 商品信息区域 */
.product-info {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.product-title {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.product-subtitle {
  font-size: 16px;
  color: #666;
  margin: 0;
}

.price-section {
  display: flex;
  align-items: baseline;
  gap: 15px;
}

.current-price {
  font-size: 32px;
  font-weight: 700;
  color: #ff6700;
}

.original-price {
  font-size: 18px;
  color: #999;
  text-decoration: line-through;
}

.product-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.tag {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  background: #f0f0f0;
  color: #666;
}

.tag.new {
  background: #e8f5e8;
  color: #52c41a;
}

.tag.hot {
  background: #fff2e8;
  color: #fa8c16;
}

.tag.recommend {
  background: #f6ffed;
  color: #52c41a;
}

.product-specs h3 {
  margin: 0 0 15px 0;
  font-size: 16px;
  color: #333;
}

.spec-options {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.spec-option {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px 15px;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
  min-width: 120px;
}

.spec-option:hover {
  border-color: #ff6700;
}

.spec-option.active {
  border-color: #ff6700;
  background: #fff7f0;
}

.spec-option.disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.spec-price {
  font-size: 14px;
  color: #ff6700;
  font-weight: 600;
  margin-top: 5px;
}

.quantity-section {
  display: flex;
  align-items: center;
  gap: 15px;
}

.quantity-section label {
  font-weight: 500;
  color: #333;
}

.stock-info {
  color: #666;
  font-size: 14px;
}

.action-buttons {
  display: flex;
  gap: 15px;
}

.action-buttons .el-button {
  flex: 1;
  height: 50px;
  font-size: 16px;
}

.service-info {
  display: flex;
  flex-direction: column;
  gap: 10px;
  padding: 15px;
  background: #f9f9f9;
  border-radius: 6px;
}

.service-item {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #666;
  font-size: 14px;
}

/* 商品描述区域 */
.product-description {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  margin: 30px 0;
  overflow: hidden;
}

.description-header {
  background: linear-gradient(135deg, #ff6700 0%, #ff8533 100%);
  padding: 25px 30px;
  color: white;
}

.description-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.header-divider {
  width: 60px;
  height: 3px;
  background: rgba(255, 255, 255, 0.3);
  margin-top: 10px;
  border-radius: 2px;
}

.description-content {
  padding: 30px;
}

.description-text {
  margin-bottom: 40px;
}

.description-paragraph {
  font-size: 16px;
  line-height: 1.8;
  color: #333;
  margin-bottom: 15px;
  text-align: justify;
}

.description-paragraph:last-child {
  margin-bottom: 0;
}

.no-description {
  text-align: center;
  padding: 60px 20px;
  color: #999;
}

.no-description-icon {
  font-size: 48px;
  margin-bottom: 20px;
}

.no-description h3 {
  margin: 0 0 10px 0;
  font-size: 20px;
  color: #666;
}

.no-description p {
  margin: 0;
  font-size: 14px;
}

/* 商品亮点 */
.product-highlights {
  margin-bottom: 40px;
  padding-top: 30px;
  border-top: 1px solid #f0f0f0;
}

.product-highlights h3 {
  margin: 0 0 20px 0;
  font-size: 20px;
  color: #333;
  font-weight: 600;
}

.highlights-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
}

.highlight-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 15px;
  background: linear-gradient(135deg, #fff7f0 0%, #fff2e8 100%);
  border-radius: 8px;
  border-left: 4px solid #ff6700;
  transition: transform 0.3s ease;
}

.highlight-item:hover {
  transform: translateY(-2px);
}

.highlight-icon {
  font-size: 20px;
}

.highlight-item span {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

/* 购买保障 */
.purchase-guarantee {
  padding-top: 30px;
  border-top: 1px solid #f0f0f0;
}

.purchase-guarantee h3 {
  margin: 0 0 25px 0;
  font-size: 20px;
  color: #333;
  font-weight: 600;
}

.guarantee-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

.guarantee-item {
  display: flex;
  align-items: flex-start;
  gap: 15px;
  padding: 20px;
  background: #fafafa;
  border-radius: 10px;
  transition: all 0.3s ease;
}

.guarantee-item:hover {
  background: #f0f0f0;
  transform: translateY(-2px);
}

.guarantee-icon {
  font-size: 24px;
  margin-top: 2px;
}

.guarantee-text h4 {
  margin: 0 0 5px 0;
  font-size: 16px;
  color: #333;
  font-weight: 600;
}

.guarantee-text p {
  margin: 0;
  font-size: 14px;
  color: #666;
  line-height: 1.5;
}

.not-found {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .product-main {
    grid-template-columns: 1fr;
    gap: 20px;
    padding: 20px;
  }

  .action-buttons {
    flex-direction: column;
  }

  .quantity-section {
    flex-wrap: wrap;
  }
}
</style>
